﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Liang.UI
{
    public class DataGridCellFormatter : IDisposable
    {

        /// <summary>
        /// 值与显示转换的委托
        /// </summary>
        /// <param name="columnName">当前列名</param>
        /// <param name="value">当前列值</param>
        /// <returns>转换后的显示值</returns>
        public delegate void CellFormatDelegate(string columnName, DataGridViewCellFormattingEventArgs value);

        /// <summary>
        /// key:列名，value：注册的委托
        /// </summary>
        private Dictionary<string, CellFormatDelegate> m_cellFormatters = new Dictionary<string, CellFormatDelegate>();

        /// <summary>
        /// 将列转换注册到具体的方法
        /// </summary>
        /// <param name="columnName">注册列名称</param>
        /// <param name="formatter">注册列转换方法</param>
        public void RegisterFormatter(string columnName, CellFormatDelegate formatter)
        {
            if (!string.IsNullOrEmpty(columnName) && formatter != null)
                m_cellFormatters[columnName] = formatter;
        }

        /// <summary>
        /// 获取注册格式化器
        /// </summary>
        /// <param name="columnName"></param>
        public CellFormatDelegate GetRegisterFormatter(string columnName)
        {
            if (m_cellFormatters.ContainsKey(columnName))
                return m_cellFormatters[columnName];
            return null;
        }

        /// <summary>
        /// 执行格式化操作
        /// </summary>
        /// <param name="columnName"></param>
        /// <param name="defaultValue"></param>
        public void RunFormatter(string columnName, DataGridViewCellFormattingEventArgs defaultValue)
        {
            CellFormatDelegate formatter = GetRegisterFormatter(columnName);
            if (formatter == null) return;
            formatter(columnName, defaultValue);
        }

        public void Dispose()
        {
            if (m_cellFormatters.Count > 0)
                m_cellFormatters.Clear();
        }
    }
}
